package com.mezizy.ifanmerchant.global;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mezizy.ifanmerchant.global.com.mezizy.ifaner.web.data.Dish;
import com.mezizy.ifanmerchant.global.com.mezizy.ifaner.web.data.Merchant;
import com.mezizy.ifanmerchant.global.com.mezizy.ifaner.web.data.Order;
import com.mezizy.ifanmerchant.global.com.mezizy.ifaner.web.data.OrderDish;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Created by Zizy on 15/2/2.
 */
public class Global {
    public static Context appContext;

    public static String stuId;
    public static String stuPwdSha;

    public static String merchantId;
    public static String merchantPwdSha;


    public static String moodleId;
    public static String moodlePwd;

    public static Map<String, Order> orderMap;
    public static Map<String, Dish> dishMap;

    public static int test_order_state = 0;

    public static boolean appState = Config.FOREGROUND;

    public static NotificationManager mNotificationManager;

    /*
    *   得到食物名称
    * */
    public static String getDishNameById(String dishId) {
        if (Global.dishMap == null) {
            getDishMapM();
        }
        String name;
        try {
            name = dishMap.get(dishId).getDishesName();

        } catch (Exception e) {
            return "No such dish";
        }
        return name;
    }


    /*
    *   得到食物列表
    * */
    public static Map<String, Dish> getDishMapM() {
        //TODO * 得到食物列表 整个方法换成用Merchant ID来读取
        Map<String, Dish> dishMapM = new HashMap<>();

        Map<String, String> map = new HashMap<>();
        map.put("iFanerUserAccount", "02132421");
        map.put("iFanerUserPassword", encrypt("123456"));
        map.put("merchantID", Global.merchantId);

        String json = "";
        try {
            json = getJsonFromWebService(map, Config.IFANER_GET_DISH_LIST);
            if (json.equals("")) return dishMapM;
        } catch (Exception e) {
            e.printStackTrace();
            return dishMapM;

        }
        Gson gson = new Gson();
        List<Dish> list = gson.fromJson(json, new TypeToken<List<Dish>>() {
        }.getType());

        for (Dish dish : list) {
            dishMapM.put(dish.getDishesId(), dish);
        }

        Global.dishMap = dishMapM;

        return dishMapM;

    }


    /*
        得到订单状态
     */
    public static int getState(String orderId) {
        //TODO * 得到订单状态
        if (orderMap == null) {
            getOrderListMerchant();
        }


        if (orderMap.get(orderId) == null) {
            return Config.STATE_EXCEPTION;
        } else {
            return orderMap.get(orderId).getTradeState();
        }
    }

    /*
    *   提示音
    * */
    public static void soundRing() {

        MediaPlayer mp = new MediaPlayer();
        mp.reset();
        try {
            mp.setDataSource(Global.appContext,
                    RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

            mp.prepare();
            mp.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
        设置订单的状态
     */
    public static boolean setState(String orderId, int state) {
        test_order_state = state;
        //TODO * 设置订单状态
        HashMap<String, String> map = getMerchantAuMap();
        map.put("orderID", orderId);
        map.put("state", String.valueOf(state));
        String json;
        try {
            json = getJsonFromWebService(map, Config.IFANER_SET_ORDER_STATE);
            getOrderListMerchant();

        } catch (Exception e) {
            e.printStackTrace();
            dismissProgress();
            return false;

        }
        boolean result=json.equals("true");
        return result;
    }

    /*
        验证密码（Version 1 为订单号），
        订单号如果存在，并且该订单状态为已经完成且没有付款，则该订单状态设置为已经付款。
     */
    public static boolean orderAuth(String orderPwd) {
        //TODO * 密码验证
//
        int state=getState(orderPwd);
        if (state != Config.STATE_FINISHED_PAID && state !=Config.STATE_CANCEL) {
            boolean result=setState(orderPwd, Config.STATE_FINISHED_PAID);
            if (result){
                return true;

            }

        }

        return false;
    }

    public static String getButtonStateS(int state) {
        switch (state) {
            case Config.STATE_CANCEL:
                return "已取消";
            case Config.STATE_CONFIRMED:
                return "已完成，去通知買家";
            case Config.STATE_EXCEPTION:
                return "发生错误";
            case Config.STATE_FINISHED_NOT_PAY:
                return "确认已收款";
            case Config.STATE_FINISHED_PAID:
                return "订单完成";
            case Config.STATE_NOT_CONFIRM:
                return "接受訂單";


        }
        return "发生错误";
    }

    public static ProgressDialog mProgressDialog;

    public static void showProgress(final Activity context, final String msg) {
        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mProgressDialog!=null){
                    mProgressDialog.dismiss();
                }
                mProgressDialog = new ProgressDialog(context);

                mProgressDialog.setTitle("提示");
                mProgressDialog.setMessage(msg);
                mProgressDialog.setIndeterminate(false);
                mProgressDialog.setCancelable(false);
                mProgressDialog.show();
            }
        });

    }

    public static void showProgress(Activity context) {
        mProgressDialog = new ProgressDialog(context);

        mProgressDialog.setTitle("提示");
        mProgressDialog.setMessage("正在提交订单");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();
    }

    public static void dismissProgress() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

    public static LinkedHashMap<String, Order> getOrderListMerchant() {
        try {
            String json = getJsonFromWebService(getMerchantAuMap(), Config.IFANER_GET_ORDER_LIST);
            Gson gson = new Gson();
            LinkedList<OrderDish> list = gson.fromJson(json, new TypeToken<LinkedList<OrderDish>>() {
            }.getType());
            LinkedHashMap<String, Order> orderMap = new LinkedHashMap<>();
            List<Dish> dishList;

            if (list == null) return null;
            for (Iterator<OrderDish> iterator = list.iterator(); iterator.hasNext(); ) {
                OrderDish orderDish = iterator.next();
                if (orderMap.get(orderDish.getTradeId()) == null) {//如果没有这个订单号码，加进去
                    dishList = new ArrayList<>();
                    dishList.add(new Dish(orderDish.getDishesId(), orderDish.getMerchantId(), orderDish.getAmount(), orderDish.getQuantity()));
                    orderMap.put(orderDish.getTradeId(), new Order(dishList, orderDish.getTradeId(), orderDish.getCusId(), orderDish.getCusName(), orderDish.getMerchantId(), orderDish.getTradeState(), orderDish.getAmount(), orderDish.getCreateTime(), orderDish.getRemarks(), orderDish.getDeliverPlace()));

                } else {//如果存在了这个订单号码
                    dishList = orderMap.get(orderDish.getTradeId()).getDishList();
                    dishList.add(new Dish(orderDish.getDishesId(), orderDish.getMerchantId(), orderDish.getAmount(), orderDish.getQuantity()));
                    orderMap.get(orderDish.getTradeId()).setDishList(dishList);
                }
                orderMap.get(orderDish.getTradeId()).setAmount(getOrderTotalPrice(dishList));

            }
            Global.orderMap = orderMap;
            return orderMap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }



    public static float getOrderTotalPrice(List<Dish> dishList) {
        float total = 0;
        for (Dish dish : dishList) {
            total += dish.getTotal();
        }
        return total;
    }

    public static String getJsonFromWebService(Map<String, String> data, String uri) {

        Connection connection = Jsoup.connect(uri).data(data).timeout(5000);
        Document document = null;
        try {
            document = connection.get();
        } catch (SocketTimeoutException e) {
            //e.printStackTrace();
            Log.i("Global", "time out");
            dismissProgress();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String json = "";
        if (document != null) {
            json = document.select("body").text();

        }


        return json;

    }

    public static boolean addUser(String stuId, String stuPwd, String stuName) throws Exception {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("iFanerUserAccount", stuId);
        map.put("iFanerUserPassword", stuPwd);
        map.put("iFanerUserName", stuName);

        String json = getJsonFromWebService(map, "http://120.96.99.54/WebService/iFanerWebService.asmx/iFanerNewUser");

        if (json.equals("true")) {
            return true;
        } else {
            return false;

        }


    }

    public static List<Dish> getDishesList(String merchantId) throws Exception {
        HashMap<String, String> map = getUserAuMap();
        map.put("merchantID", merchantId);

        String json = getJsonFromWebService(map, "http://120.96.99.54/WebService/iFanerWebService.asmx/getDishesList");

        Gson gson = new Gson();
        List<Dish> list = gson.fromJson(json, new TypeToken<List<Dish>>() {
        }.getType());

        return list;
    }

    public static HashMap<String, String> getUserAuMap() {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("iFanerUserAccount", Global.stuId);
        map.put("iFanerUserPassword", Global.stuPwdSha);
        return map;
    }

    public static HashMap<String, String> getMerchantAuMap() {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("iFanerMerchantID", Global.merchantId);
        map.put("iFanerMerchantrPassword", Global.merchantPwdSha);
        return map;
    }

    public static List<Merchant> getMerchantList() throws Exception {
        HashMap<String, String> map = getUserAuMap();
//
//
//        map.put("iFanerUserAccount",  "test0");
//        map.put("iFanerUserPassword","00130362");


        String json = getJsonFromWebService(map, "http://120.96.99.54/WebService/iFanerWebService.asmx/getMerchantList");

        Gson gson = new Gson();
        @SuppressWarnings("rawtypes")
        List<Merchant> list = gson.fromJson(json, new TypeToken<List<Merchant>>() {
        }.getType());
        return list;


    }

    public static String encrypt(String strSrc) {
        MessageDigest md = null;
        String strDes = null;


        byte[] bt = strSrc.getBytes();
        try {

            String encName = "SHA-256";

            md = MessageDigest.getInstance(encName);
            md.update(bt);
            strDes = bytes2Hex(md.digest()); // to HexString
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
        return strDes;
    }


    public static String bytes2Hex(byte[] bts) {
        String des = "";
        String tmp = null;
        for (int i = 0; i < bts.length; i++) {
            tmp = (Integer.toHexString(bts[i] & 0xFF));
            if (tmp.length() == 1) {
                des += "0";
            }
            des += tmp;
        }
        return des;
    }


    static public Toast toast;


    public static void showToast(final String str, Activity activity) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showToast(str);
            }
        });
    }

    public static void showToast(final String str, final int during, Activity activity) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showToast(str, during);
            }
        });
    }

    public static void showToast(String str) {
        showToast(str, Toast.LENGTH_SHORT);
    }

    public static void showToast(String str, int during) {
        if (toast == null) {
            toast = Toast.makeText(Global.appContext, str, during);
        } else {
            toast.setText(str);

        }

        toast.show();
    }


    public static boolean moodleAuthorize(String stuId, String password) {
        /* 建立HTTP POST連線 */
        HttpPost httpRequest = new HttpPost(Config.MOODLE_LOG_IN_URI);

		/* POST運作傳送變數必須用NameValuePair[]陣列儲存 */

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("id", stuId));
        params.add(new BasicNameValuePair("password", password));
        params.add(new BasicNameValuePair("ip", "120.96.99.54"));
        params.add(new BasicNameValuePair("idtype", "s"));
        params.add(new BasicNameValuePair("type", "1"));

        try {

			/* 發出HTTP Request */
            httpRequest.setEntity(new UrlEncodedFormEntity(params, "big5"));

			/* 取得HTTP Response */
            HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);

			/* 若狀態碼為200則OK */
            if (httpResponse.getStatusLine().getStatusCode() == 200) {

				/* 取出回應字串 */
                String strResult = EntityUtils.toString(httpResponse.getEntity());

				/* 檢驗帳號密碼是否正確 (用mobilepassword的值檢測：0為正確, 1為錯誤) */
                int index = strResult.indexOf("mobilepassword");
                int LoginCheck = Integer.parseInt(strResult.substring(index + 17, index + 18));
                if (LoginCheck == 0) {
                    return Config.MOODLE_LOG_IN_SUCCESS;
                } else {
                    return Config.MOODLE_LOG_IN_FAILED;
                }
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return Config.MOODLE_LOG_IN_FAILED;
    }


    public static int userAuthorize(String stuId, String stuPwdSha) {

        HashMap<String, String> map = new HashMap<String, String>();
        map.put("iFanerUserAccount", stuId);
        map.put("iFanerUserPassword", stuPwdSha);

        try {
            String result = getJsonFromWebService(map, Config.IFANER_LOG_IN_URI);
            if (result.equals("true")) {
                return Config.IFANER_LOG_IN_SUCCESS;
            } else {
                return Config.IFANER_LOG_IN_FAILED_AU;
            }
        } catch (Exception e) {
            e.printStackTrace();

            return Config.IFANER_LOG_IN_FAILED_INTERNET;

        }

    }

    public static int merchantAuthorize(String merchantId, String merchantPwdSha) {

        HashMap<String, String> map = new HashMap<String, String>();
        map.put("iFanerMerchantID", merchantId);
        map.put("iFanerMerchantPassword", merchantPwdSha);

        try {
            String result = getJsonFromWebService(map, Config.IFAN_MERCHANT_LOG_IN_URI);
            if (result.equals("true")) {
                return Config.IFANER_LOG_IN_SUCCESS;
            } else {
                return Config.IFANER_LOG_IN_FAILED_AU;
            }
        } catch (Exception e) {
            e.printStackTrace();

            return Config.IFANER_LOG_IN_FAILED_INTERNET;

        }

    }
}


